using System;
using System.Linq;
using Demo.Db;
using Demo.Model;
using Microsoft.EntityFrameworkCore;

namespace Demo.Repository
{
    public class EfRepository<T> : IRepository<T> where T:EntityBase
    {

        private readonly Demosoft _db;
        private readonly DbSet<T> _table;

        public EfRepository(){
            _db=new Demosoft();
            _table=_db.Set<T>();     
            
               }
        public IQueryable<T> Table {
            get{
                return _table as IQueryable<T>;
            }
        }

        public void Delete(int id)
        {
            var entity=_table.Where(x=>x.Id==id).FirstOrDefault();
            if(entity!=null){
                entity.IsDeleted=true;
                entity.UpdatedTime=DateTime.Now;
                
            }
            _table.Update(entity);
            _db.SaveChanges();
        }

        public T GetById(int id)
        {
             var entity=_table.Where(x=>x.Id==id).FirstOrDefault();
             return entity;
        }

        public void Insert(T entity)
        {
            entity.IsActived=true;
            entity.IsDeleted=false;
            entity.CreatedTime=DateTime.Now;
            entity.UpdatedTime=DateTime.Now;
            entity.Creator=0;
            entity.DisplayOrder=0;
            _table.Add(entity);
            _db.SaveChanges();
        }

        public void Update(T entity)
        {
            entity.UpdatedTime=DateTime.Now;
            _table.Update(entity);
            _db.SaveChanges();
        }
    }
}
